package zd.cornermemory.utils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import java.util.TimerTask;

import zd.cornermemory.fragment.TimerFragment;

public class Timer {
	public static int state = 0;	//0-就绪 1-计时中 2-观察中 3-停止

	public long time, timeStart, timeEnd;
	protected java.util.Timer myTimer;
	protected TimerTask timerTask = null;
	TimerFragment dct;
	TimeHandler   timeh;

	public Timer(TimerFragment dct) {
		this.dct = dct;
		timeh = new TimeHandler();
		myTimer = new java.util.Timer();
	}


	private class ClockTask extends TimerTask {
		@Override
		public void run() {
			time = System.currentTimeMillis() - timeStart;
			timeh.sendEmptyMessage(0);
		}
	}


	public long getTime() {
		return time;
	}

	@SuppressLint("HandlerLeak")
	class TimeHandler extends Handler {
		public void handleMessage (Message msg) {
			if (100 <= state) {return;}
			if(msg.what == 1) dct.setTimerColor(0xff00ff00);
			else if(msg.what == 2) {
				dct.setTimerText(Statistics.timeToString((int)time));
			}else if(state == 1) {
				dct.setTimerText(Statistics.timeToString((int)time));
			}

		}
	}

	public void count2() {
		if(state==1) {
			time = 0;
			timeStart = System.currentTimeMillis();
			timerTask = new ClockTask();
			myTimer.schedule(timerTask, 0, 17);
		}
		else if(state == 3) {
			timerTask.cancel();
			timerTask = null;
			new Thread(new Runnable() {
				public void run() {
					try {
						Thread.sleep(23);
					} catch (InterruptedException e) { }
					timeh.sendEmptyMessage(2);
				}
			}).start();
		}
	}
}
